package com.song.elasticsearch.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.stream.FileImageOutputStream;
import java.io.*;
import java.net.URLDecoder;

/**
 * @Description: TODO
 * @Author: HuYa
 * @Date: 2022/4/18 0018
 **/
public class FileTools {
    private static final Logger logger = LoggerFactory.getLogger(FileTools.class);
    public static final boolean isWin = System.getProperty("os.name").toLowerCase().contains("win");
    public static final boolean isLinux = System.getProperty("os.name").toLowerCase().contains("linux");

    public static String img_base64(MultipartFile imageFile) {
        String imgBase64 = null;
        try {
            imgBase64 = new String(Base64.encodeBase64(imageFile.getBytes()));
        } catch (FileNotFoundException e) {
            logger.error("文件异常，请重新上传！", e);
        } catch (IOException e) {
            logger.error("文件解析错误！", e);
        }
        return imgBase64;
    }

    public static boolean copyFile(String sourceFile, String targetFile){
        int index = targetFile.lastIndexOf("/");
        String targetDir = targetFile.substring(0, index);
        if (!isExists(targetDir)){
            new File(targetDir).mkdirs();
        }
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), "utf-8"));
             PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "utf-8"))){
            String line = "";
            while ((line = br.readLine()) != null){
                pw.println(line);
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    public static boolean copyImage(String sourceFile, String targetFile){
        int index = targetFile.lastIndexOf("/");
        String targetDir = targetFile.substring(0, index);
        if (!isExists(targetDir)){
            new File(targetDir).mkdirs();
        }
        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(targetFile)) {
            byte[] buff = new byte[1024];
            int len=-1;
            while((len = fis.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }
            fos.flush();
            return true;
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
        return false;
    }

    public static boolean deleteFile(File dir){
        if (dir.isDirectory()){
            File[] files = dir.listFiles();
            if (files != null && files.length > 0){
                for(File file : files){
                    deleteFile(file);
                }
            }
        }
        dir.delete();
        return true;
    }

    /**
     * @title fileStreamToBytes
     * @description 将文件转化为字节
     * @param @param file
     * @param @return
     * @return byte[]
     * @throws
     */
    public static byte[] fileStreamToBytes(File file) {
        byte[] bytecontent = null;
        try {
            int bufLength = (int) file.length();
            FileInputStream in = new FileInputStream(file);
            byte[] buf = new byte[bufLength];
            int readLen;
            ByteArrayOutputStream byout = new ByteArrayOutputStream();
            while ((readLen = in.read(buf, 0, bufLength)) > 0) {
                byout.write(buf, 0, bufLength);
            }
            in.close();
            bytecontent = byout.toByteArray();
            return bytecontent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File bytesToFileStream(byte[] bytes, String path) {
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(bytes);
            imageOutput.close();
            return new File(path);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public static Boolean isExists(String path){
        File file = new File(path);
        return file.exists();
    }

    public static void mkdirs(String path){
        if (!isExists(path)){
            new File(path).mkdirs();
        }
    }

    public static String getFilePath(String fileName){
        String filePath = ClassUtils.getDefaultClassLoader().getResource(fileName).getPath();
        try{
            filePath = URLDecoder.decode(filePath, "UTF-8");
            if (isWin){
                filePath = filePath.substring(1);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("路径获取异常！{}", e);
        }
        return  filePath;
    }
}
